package com.lzxzjy.web.servlet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lzxzjy.pojo.Book;
import com.lzxzjy.pojo.BorrowInfo;
import com.lzxzjy.pojo.PageBean;
import com.lzxzjy.pojo.Reader;
import com.lzxzjy.serivce.BookService;
import com.lzxzjy.serivce.BorrowInfoService;
import com.lzxzjy.serivce.ReaderService;
import com.lzxzjy.serivce.impl.BookServiceImpl;
import com.lzxzjy.serivce.impl.BorrowINfoServiceImpl;
import com.lzxzjy.serivce.impl.ReaderServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.List;

@WebServlet("/borrowInfo/*")
public class BorrowInfoServlet extends BaseServlet {

    private final BorrowInfoService borrowInfoService = new BorrowINfoServiceImpl();

    private final ReaderService readerService = new ReaderServiceImpl();

    private final BookService bookService = new BookServiceImpl();

    private int availabilityOfBooks(int readerId, int num) {
        PageBean<BorrowInfo> borrowInfoPageBean = borrowInfoService.selectBorrowInfoByPageAndBookTerms(new BorrowInfo(null, "%%", readerId, "%%", "", "", null), 1, 10);
        if (borrowInfoPageBean.getTotalCount() + num > 10) {
            return 0;
        }
        for(BorrowInfo b : borrowInfoPageBean.getRows()) {
            if (Double.parseDouble(b.getArrears()) > 0) {
                return -1;
            }
        }
        return 1;
    }

    public void borrowBooks(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        BufferedReader borrowInfoReader = request.getReader();
        String borrowInfoLine = borrowInfoReader.readLine();
        JSONObject borrowBooks = JSON.parseObject(borrowInfoLine);
        List<Integer> bookIds = (List<Integer>) borrowBooks.get("bookIds");
        int availabilityOfBook = availabilityOfBooks((int)borrowBooks.get("readerId"),bookIds.size());
        response.setContentType("text/plain; charset=utf-8");
        if (availabilityOfBook == 0) {
            response.getWriter().write("超过 10 本，请先归还一些书");
        } else if (availabilityOfBook == -1) {
            response.getWriter().write("有书已过期，请先缴纳欠费");
        } else {
            borrowInfoService.borrowBooks((Integer) borrowBooks.get("readerId"), bookIds);
            for(int bookId: bookIds) {
                Book book = (bookService.selectBookByPageAndTerms(new Book(bookId, "%%", "%%", "%%", "%%", null, "%%", "%%", null), 1, 1)).getRows().get(0);
                book.setBookState(10);
                bookService.updateBookById(book);
            }
            response.getWriter().write("借书成功");
        }
    }

    public void selectBorrowInfoByPageAndTerms(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        BufferedReader borrowInfoReader = request.getReader();
        String borrowInfoLine = borrowInfoReader.readLine();
        int currentPage = Integer.parseInt(request.getParameter("currentPage"));
        int pageSize = Integer.parseInt(request.getParameter("pageSize"));

        BorrowInfo borrowInfo = JSON.parseObject(borrowInfoLine, BorrowInfo.class);
        borrowInfo.setBookName("%" + borrowInfo.getBookName() + "%");
        borrowInfo.setReaderName("%" + borrowInfo.getReaderName() + "%");

        PageBean<BorrowInfo> borrowInfoPageBean = borrowInfoService.selectBorrowInfoByPageAndBookTerms(borrowInfo, currentPage, pageSize);

        String borrowInfoPageBeanLine = JSON.toJSONString(borrowInfoPageBean);

        response.setContentType("text/json;charset=utf-8");
        response.getWriter().write(borrowInfoPageBeanLine);
    }

    private int[] toIntArrayBookIds(String borrowInfoLine) {
        BorrowInfo[] borrowInfos = JSON.parseObject(borrowInfoLine, BorrowInfo[].class);
        StringBuilder stringIds = new StringBuilder("[");
        for (BorrowInfo borrowInfo : borrowInfos) {
            stringIds.append(borrowInfo.getBookId());
            stringIds.append(",");
        }
        stringIds.replace(stringIds.length() - 1, stringIds.length(), "]");
        return JSON.parseObject(String.valueOf(stringIds), int[].class);
    }

    public void lostBooks(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        BufferedReader borrowInfoReader = request.getReader();
        String borrowInfoLine = borrowInfoReader.readLine();
        int[] bookIds = toIntArrayBookIds(borrowInfoLine);
        boolean isSuccess = borrowInfoService.lostBooks(bookIds);
        if (isSuccess) {
            response.getWriter().write("success");
        } else {
            response.getWriter().write("failure");
        }
    }

    public void lostBook(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        int bookId = Integer.parseInt(request.getParameter("bookId"));
        boolean isSuccess = borrowInfoService.lostBook(bookId);
        if (isSuccess) {
            response.getWriter().write("success");
        } else {
            response.getWriter().write("failure");
        }
    }

    public void returnBooks(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        BufferedReader borrowInfoReader = request.getReader();
        String borrowInfoLine = borrowInfoReader.readLine();
        int[] bookIds = toIntArrayBookIds(borrowInfoLine);
        boolean isSuccess = borrowInfoService.returnBooks(bookIds);
        if (isSuccess) {
            response.getWriter().write("success");
        } else {
            response.getWriter().write("failure");
        }
    }

    public void returnBook(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        int bookId = Integer.parseInt(request.getParameter("bookId"));
        boolean isSuccess = borrowInfoService.returnBook(bookId);
        if (isSuccess) {
            response.getWriter().write("success");
        } else {
            response.getWriter().write("failure");
        }
    }
}
